<template>
  <div class="bgc-white p16">
    <div v-if="groupId" class="flex-center bgc-white mb16">
      <a-popover v-model="groupSelectVisible" trigger="click" placement="bottom" style="cursor: pointer">
        <i class="iconfont icon-gongsi-2-line2x fs16 mr8" style="color: #55565d" />
        {{ groupName }}
        <i class="iconfont icon-swap2x fs16 ml8" style="color: var(--primary)" />
        <div slot="content">
          <a-tree :treeData="groupLst" :selectedKeys="[groupId]" @select="onGroupChange" />
        </div>
      </a-popover>
      <a-range-picker
        :value="dateRange"
        :placeholder="['开始月份', '结束月份']"
        :mode="['month', 'month']"
        format="YYYY-MM"
        class="ml16"
        style="width: 240px"
        @panelChange="onPanelChange"
      />
    </div>
    <div v-show="countLstByGroupLoaded" class="flex-center">
      <div class="pv12 ph24 br4 mr16" style="background: rgba(190, 190, 190, 0.1); flex-shrink: 0">
        <div>销售提成统计</div>
        <div class="fs16 fw500 ta-center mt4">{{ count }}</div>
      </div>
      <div class="flex-center pv12 ph24 br4" style="flex: 1; overflow-x: auto; background: rgba(190, 190, 190, 0.1)">
        <!-- <div key="fzzs" class="ta-center ph12" style="height: 49px; width: 160px">
          <div class="ellipsis">分组直属人员</div>
          <div class="fs16 fw500 mt4">{{ count2 }}</div>
        </div> -->
        <template v-if="countLstByGroup.length > 0">
          <div v-for="pane in countLstByGroup" :key="pane.key" class="ta-center ph12" style="height: 49px; width: 160px">
            <a-tooltip :title="pane.key">
              <div class="ellipsis">{{ pane.key }}</div>
            </a-tooltip>
            <div class="fs16 fw500 mt4">{{ pane.value }}</div>
          </div>
        </template>
      </div>
    </div>
    <div v-show="countLstByGroup.length > 0" class="p16">
      <div class="flex-center-between">
        <div>
          <div class="flex-center title">销售分组提成</div>
          <div class="fs12 pl10 mt4">单位：元</div>
        </div>
      </div>
      <div id="group_chart" style="width: 100%; height: 140px"></div>
    </div>
    <div v-show="countLstByMonth.length > 0" class="p16">
      <div class="flex-center-between">
        <div>
          <div class="flex-center title">销售提成趋势</div>
          <div class="fs12 pl10 mt4">单位：元</div>
        </div>
      </div>
      <div id="month_chart" style="width: 100%; height: 140px"></div>
    </div>
    <div class="mt24">
      <a-space>
        <a-input-search
          v-model="saleNameOrPhoneOrIdCard"
          placeholder="搜索销售名称/联系电话/身份证号"
          style="width: 260px"
          @change="loadList"
        />
        <a-cascader
          v-model="region"
          :options="common.areaList"
          changeOnSelect
          :show-search="{ filter }"
          placeholder="所在地区"
          allowClear
          style="width: 120px"
          @change="loadList"
        />
      </a-space>
    </div>
    <a-table
      :dataSource="recordLst"
      :columns="tongjiColumns"
      :pagination="pagination"
      :rowKey="(record, idx) => `${record.salePhone}_${idx}`"
      class="mt24"
      @change="onTableChange"
    >
      <template slot="uc" slot-scope="text, record">
        <div class="ellipsis pointer" style="width: 200px" @click="$refs.uc.onItemClick(record.saleUserId)">
          <a>{{ text }}</a>
        </div>
      </template>
    </a-table>
    <UserCompany ref="uc" />
  </div>
</template>
<script>
import { rebateOverviewListReq, rebateOverviewGroupReq, rebateOverviewMonthReq, selectGroupTreeReq, selectDefaultGroupIdReq } from "../api";
import echarts from "echarts";
import { tongjiColumns, formatGroupTreeForXS, genGroupOptions, genMonthOptions } from "../funcs";
import moment from "moment";
import _ from "lodash";
import { mapState } from "vuex";
import UserCompany from "../components/userCompany.vue";
export default {
  name: "",
  components: { UserCompany },
  mixins: [],
  props: {},
  data() {
    return {
      countLstByGroupLoaded: false,
      region: null,
      saleNameOrPhoneOrIdCard: "",
      groupSelectVisible: false,
      groupId: "",
      groupName: "",
      tongjiColumns,
      groupChart: null,
      monthChart: null,
      dateRange: [moment().subtract(5, "months"), moment()],
      dateRangeTemp: null,
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      recordLst: [],
      groupLst: [],
      count: 0,
      count2: 0,
      countLstByGroup: [],
      countLstByMonth: []
    };
  },
  computed: {
    ...mapState(["common"])
  },
  watch: {},
  created() {
    this.loadGroups();
  },
  mounted() {},
  methods: {
    filter(inputValue, path) {
      return path.some((option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    },
    onGroupChange(selectedKeys, options) {
      if (selectedKeys[0]) {
        const dataRef = options.node.dataRef;
        if (this.groupId !== dataRef.value) {
          this.dateRangeTemp = this.dateRange;
          this.groupId = dataRef.value;
          this.groupName = dataRef.title;
          this.pagination.current = 1;
          this.onSearchChange();
        }
      }
      this.groupSelectVisible = false;
    },
    loadGroups() {
      selectGroupTreeReq().then(async (res) => {
        await selectDefaultGroupIdReq()
          .then((res) => {
            if (res.data) {
              this.groupId = res.data.id;
              this.groupName = res.data.name;
            }
          })
          .catch((err) => {
            console.log("selectDefaultGroupIdReq", err);
          });
        this.groupLst = formatGroupTreeForXS(res.data);
        this.onSearchChange();
      });
    },
    onPanelChange(value) {
      this.dateRangeTemp = this.dateRange;
      this.dateRange = value;
      this.pagination.current = 1;
      this.onSearchChange();
    },
    onSearchChange() {
      const params = {
        groupId: this.groupId
      };
      if (this.dateRange && this.dateRange.length > 0) {
        const dates = this.dateRange.map((item) => item.format("YYYY-MM"));
        params["beginTime"] = dates[0];
        params["endTime"] = dates[1];
      }
      this.countLstByGroupLoaded = false;
      rebateOverviewGroupReq(params)
        .then((res) => {
          this.count = res.data.allAmount;
          this.count2 = res.data.directlyUnder;
          this.countLstByGroup = Object.keys(res.data.subordinate).map((key) => ({
            key,
            value: res.data.subordinate[key]
          }));
          this.countLstByGroupLoaded = true;
          this.groupChart = null;
          setTimeout(() => {
            echarts.init(document.getElementById("group_chart")).dispose();
            this.groupChart = echarts.init(document.getElementById("group_chart"));
            const color = document.body.style.getPropertyValue("--primary");
            this.groupChart.setOption(genGroupOptions(this.countLstByGroup, color));
          }, 0);
        })
        .catch((err) => {
          this.groupChart = null;
          this.count = 0;
          this.count2 = 0;
          this.countLstByGroup = [];
          this.countLstByGroupLoaded = true;
          console.log("rebateOverviewGroupReq", err);
          if (this.dateRangeTemp) {
            this.dateRange = this.dateRangeTemp;
          }
        });
      rebateOverviewMonthReq(params)
        .then((res) => {
          const temp = Object.keys(res.data.monthAmount).map((key) => ({
            key,
            value: res.data.monthAmount[key]
          }));
          this.countLstByMonth = _.orderBy(temp, ["key"], ["asc"]);
          this.monthChart = null;
          setTimeout(() => {
            echarts.init(document.getElementById("month_chart")).dispose();
            this.monthChart = echarts.init(document.getElementById("month_chart"));
            const color = document.body.style.getPropertyValue("--primary");
            this.monthChart.setOption(genMonthOptions(this.countLstByMonth, color));
          }, 0);
        })
        .catch((err) => {
          this.monthChart = null;
          this.countLstByMonth = [];
          console.log("rebateOverviewMonthReq", err);
          if (this.dateRangeTemp) {
            this.dateRange = this.dateRangeTemp;
          }
        });
      this.pagination.current = 1;
      this.loadList();
    },
    onTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.loadList();
    },
    loadList() {
      const params = {
        groupId: this.groupId,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      if (this.dateRange && this.dateRange.length > 0) {
        const dates = this.dateRange.map((item) => item.format("YYYY-MM"));
        params["beginTime"] = dates[0];
        params["endTime"] = dates[1];
      }
      if (this.saleNameOrPhoneOrIdCard) {
        params["saleNameOrPhoneOrIdCard"] = this.saleNameOrPhoneOrIdCard;
      }
      if (this.region) {
        params["region"] = this.region[this.region.length - 1];
      }
      rebateOverviewListReq(params)
        .then((res) => {
          this.recordLst = res.data.entities;
          this.pagination.total = res.data.entityCount;
        })
        .catch((err) => {
          console.log("rebateOverviewListReq", err);
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.title {
  position: relative;
  &:before {
    content: "";
    border-radius: 4px;
    height: 16px;
    width: 4px;
    display: inline-block;
    margin-right: 8px;
    background-color: var(--primary);
  }
}
</style>
